package com.xl.rentkeeper.db.orm;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.xl.rentkeeper.db.orm.util.ManifestHelper;
import com.xl.rentkeeper.db.orm.util.SugarCursorFactory;
import com.xl.rentkeeper.log.QLog;


public class DBOpenHelper extends SQLiteOpenHelper {
    private final SchemaGenerator schemaGenerator;
    private SQLiteDatabase sqLiteDatabase;

    public DBOpenHelper(Context context,long uid) {
        super(context, DBContext.getDBName(context,uid),
                new SugarCursorFactory(ManifestHelper.getDebugEnabled(context)), ManifestHelper.getDatabaseVersion(context));
        schemaGenerator = new SchemaGenerator(context);
        QLog.d("db.openhelper", "construct");
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        long start = System.currentTimeMillis();
        schemaGenerator.createDatabase(sqLiteDatabase);
        QLog.d("db.onCreate", "elapse " + (System.currentTimeMillis() - start));
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        long start = System.currentTimeMillis();
        schemaGenerator.doUpgrade(sqLiteDatabase, oldVersion, newVersion);
        QLog.d("db.onUpgrade", " ov " + oldVersion + " nv " + newVersion + " elapse " + (System.currentTimeMillis() - start));

    }

    public synchronized SQLiteDatabase getDB() {
        if (this.sqLiteDatabase == null) {
            this.sqLiteDatabase = getWritableDatabase();
        }
        return this.sqLiteDatabase;
    }
}
